﻿using System.Diagnostics;
using AntdUI;
using Sunny.UI;
using MSWord = Microsoft.Office.Interop.Word;
namespace DataAcquisition
{
    public partial class ReportForm : BaseForm
    {
        #region 属性

        /// <summary>
        /// 是否可以编辑
        /// </summary>
        public bool edit;

        /// <summary>
        /// 校验编辑权限
        /// </summary>
        public bool checkEditAuthority;

        /// <summary>
        /// 项目
        /// </summary>
        public ProjectItem projectItem;

        /// <summary>
        /// 试压记录
        /// </summary>
        public TestRecord testRecord;

        /// <summary>
        /// 模板
        /// </summary>
        public Template template;

        /// <summary>
        /// 曲线截图路径
        /// </summary>
        public string chartImagePath;

        #endregion

        #region 自定义方法

        private void SetupInfo()
        {
            string projectNumber = string.Empty;
            if (projectItem is not null)
            {
                ProjectNumberLabel.Text = projectItem.Number;
                ProjectNameLabel.Text = projectItem.Name;
                StakeMarkLabel.Text = projectItem.StakeMark;
                CompanyLabel.Text = projectItem.Company;
                PipeSpecificationIabel.Text = projectItem.PipeSpecification;
                DesignPressureLabel.Text = projectItem.DesignPressure.ToString();
                PipeLengthLabel.Text = projectItem.PipeLength.ToString();
                MediumLabel.Text = projectItem.Medium;
                projectNumber = projectItem.Number;
            }

            string testRecordNumber = string.Empty;
            if (testRecord is not null)
            {
                TimeInput.Text = testRecord.StartTime.ToString("yyyy-MM-dd HH时") + " 至 " + testRecord.EndTime.ToString("yyyy-MM-dd HH时");
                testRecordNumber = testRecord.number.ToString();
            }

            if (template is not null)
            {
                IntensityPressureInput.Text = template.IntensityStagePressure.ToString();
                IntensityTimeInput.Text = template.IntensityStageTime.ToString() + template.IntensityStageTimeUnit;
                IntensityDiffenceInput.Text = "0";

                RigorPressureInput.Text = template.RigorStagePressure.ToString();
                RigortTimeInput.Text = template.RigorStageTime.ToString() + template.RigorStageTimeUnit;
                RigorDiffenceInput.Text = "0";
            }

            IntensityResultSelect.Text = "合格";
            RigorResultSelect.Text = "合格";

            string name = string.Format("{0}-{1}.png", testRecordNumber, projectNumber);

            chartImagePath = Path.Combine(chartImagePath, name);

            PictureBox1.Image = Image.FromFile(chartImagePath);
        }

        private void FindAndReplace(MSWord.Document doc, string findText, string replaceText)
        {
            // 将模板设为可编辑
            doc.Activate();

            // 执行查找和替换操作
            // 可以使用其他查找和替换方法，例如使用Range对象
            object findObj = findText;
            object replaceObj = replaceText;
            object missingObj = Type.Missing;
            doc.Content.Find.Execute(ref findObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
            ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref replaceObj, ref missingObj,
            ref missingObj, ref missingObj, ref missingObj, ref missingObj);
        }

        public void ReplaceImage(MSWord.Document doc2)
        {
            // 创建Word应用程序对象
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            wordApp.Visible = true;

            // 查找文档中的文本
            MSWord.Range range = doc2.Content;
            range.Find.Text = "Image";
            // 定位到第一个匹配项
            range.Find.Execute();
            if (range.Find.Found)
            {
                // 插入图片
                MSWord.InlineShape shape = range.InlineShapes.AddPicture(chartImagePath, LinkToFile: false, SaveWithDocument: true);

                // 调整图片大小和位置
                shape.Width = range.Font.Size * 2;
                shape.Height = range.Font.Size * 2;

                // 删除文本
                range.Text = "";
            }
        }
        #endregion

        #region 系统方法
        public ReportForm()
        {
            InitializeComponent();
            Header.Text = "试压报告";
        }
        #endregion

        private void ReportForm_Load(object sender, EventArgs e)
        {
            SetupInfo();
        }

        /// <summary>
        /// 重载编辑权限
        /// </summary>
        public void ReloadEditAuthority()
        {
            string code = RegisterClass.ReadSetting("", "Code", "-1");
            if (code == "-1")
            {
                RegistrationCodeForm();
            }
            else
            {
                string time = RegisterClass.StartTime();
                DateTime startDateTime = new DateTime();
                if (time.Length > 0)
                {
                    long timestamp = time.ToLong(); // 时间戳

                    DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
                    startDateTime = dateTimeOffset.LocalDateTime;
                }

                DateTime endDateTime = new DateTime();
                time = RegisterClass.EndTime();
                if (time.Length > 0)
                {
                    long timestamp = time.ToLong(); // 时间戳
                    DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
                    endDateTime = dateTimeOffset.LocalDateTime;
                }

                DateTime nowDateTime = DateTime.Now;
                int result1 = nowDateTime.CompareTo(startDateTime);
                int result2 = nowDateTime.CompareTo(endDateTime);
                if (result1 > 0 && result2 < 0)
                {
                    EditResult(false);
                }
                else
                {
                    RegistrationCodeForm();
                    EditResult(true);
                }
            }
        }

        private void EditResult(bool res) 
        {
            IntensityResultSelect.ReadOnly = res;
            RigorResultSelect.ReadOnly = res;
        }

        private void ConfirmButton_Click(object sender, EventArgs e)
        {

            AntdUI.Spin.open(this, "保存报告...", (config) =>
            {
                Thread.Sleep(100);
                ITask.Run(() =>
                {
                    string templatePath = "D:\\template.docx";
                    string? name = projectItem.Name;
                    if (name == null)
                    {
                        name = "试压报告";
                    }
                    string outputPath = string.Format("D:\\{0}-{1}.docx", DateTime.Now.ToString("yyyyMMdd"), name);
                    // 创建Word应用程序对象
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    // 打开模板文档
                    MSWord.Document wordDoc = wordApp.Documents.Open(templatePath);
                    {
                        //这里就是要干什么事了，替换文字，添加内容等操作
                        // 替换模板中的文本
                        FindAndReplace(wordDoc, "Project", projectItem.Name);
                        FindAndReplace(wordDoc, "Number", projectItem.Number);
                        FindAndReplace(wordDoc, "StakeMark", projectItem.StakeMark);
                        FindAndReplace(wordDoc, "PipeSpecification", projectItem.PipeSpecification);
                        FindAndReplace(wordDoc, "DesignPressure", projectItem.DesignPressure.ToString() + "MPa");
                        FindAndReplace(wordDoc, "PipeLength", projectItem.PipeLength.ToString());
                        FindAndReplace(wordDoc, "Medium", projectItem.Medium);
                        FindAndReplace(wordDoc, "Time", TimeInput.Text);

                        FindAndReplace(wordDoc, "IntensityPressure", template.IntensityStagePressure.ToString() + "MPa");
                        string time = template.IntensityStageTime.ToString() + template.IntensityStageTimeUnit;
                        FindAndReplace(wordDoc, "IntensityTime", time);
                        FindAndReplace(wordDoc, "IntensityDiffence", "0");

                        FindAndReplace(wordDoc, "RigorPressure", template.RigorStagePressure.ToString() + "MPa");
                        time = template.RigorStageTime.ToString() + template.RigorStageTimeUnit;
                        FindAndReplace(wordDoc, "RigorTime", time);
                        FindAndReplace(wordDoc, "RigorDiffence", "0");

                        string res = "不合格";
                        if (IntensityResultSelect.Text == "合格" && RigorResultSelect.Text =="合格")
                        {
                            res = "合格";
                        }
                        FindAndReplace(wordDoc, "Result", res);

                        ReplaceImage(wordDoc);
                    }

                    // 保存为新文档
                    wordDoc.SaveAs2(outputPath);
                    wordDoc.Close();
                    // 关闭Word应用程序对象
                    wordApp.Quit();

                });
            }, () =>
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    this.Close();
                }));
            });
        }

        private void RegistrationCodeForm()
        {
            AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", "请输入权限码")
            {
                OnOk = config =>
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        RegistrationCodeForm frm = new RegistrationCodeForm();
                        frm.Owner = this;
                        frm.ShowDialog();

                    }));
                    return true;
                },
                CancelText = null,
                OkText = "确定"
            });
        }

        private void IntensityResultSelect_DoubleClick(object sender, EventArgs e)
        {
            ReloadEditAuthority();
        }
    }

}
